// // 单个中间件的执行
// function applyMiddeware(fn) {
//   return function (createStore) {
//     return function (reducer) {
//       const store = createStore(reducer);

//       let dispatch;

//       const middlewareAPI = {
//         getState: store.getState,
//         dispatch: (action) => dispatch(action),
//       };
//       // fn 用户的中间件函数
//       dispatch = fn(middlewareAPI)(store.dispatch);
//       return {
//         ...store,
//         dispatch,
//       };
//     };
//   };
// }

import compose from "./compose";
// 多个中间件的组合执行
function applyMiddeware(...middlewares) {
  return function (createStore) {
    return function (reducer, preloadedState) {
      const store = createStore(reducer, preloadedState);

      let dispatch;

      const middlewareAPI = {
        getState: store.getState,
        dispatch: (action) => dispatch(action),
      };
      // // middlewares 用户的中间件函数
      // dispatch = middlewares(middlewareAPI)(store.dispatch);
      // 多个中间件组合使用
      const chain = middlewares.map((middleware) => middleware(middlewareAPI));
      dispatch = compose(...chain)(store.dispatch);
      return {
        ...store,
        dispatch,
      };
    };
  };
}

export default applyMiddeware;
